<template>
  <div class="cart-container">
    <!-- 页面标题 -->
    <div class="cart-header">
      <h2>我的购物车</h2>
      <button @click="handleClearAll" class="clear-btn" :disabled="cartItems.length === 0">
        清空购物车
        <i class="icon-trash"></i>
      </button>
    </div>

    <!-- 购物车列表 -->
    <div class="cart-list" v-if="cartItems.length > 0">
      <!-- 列表头部 - 美化部分 -->
      <div class="cart-list-header">
        <div class="header-select">
          <label class="checkbox-label">
            <input type="checkbox" v-model="selectAll" class="custom-checkbox">
            <span class="checkmark"></span>
            全选
          </label>
        </div>
        <div class="header-info">商品信息</div>
        <div class="header-price">单价</div>
        <div class="header-quantity">数量</div>
        <div class="header-subtotal">小计</div>
        <div class="header-operation">操作</div>
      </div>

      <!-- 商品项 -->
      <transition-group name="cart-item" tag="div">
        <div class="cart-item" v-for="item in cartItems" :key="item.id" :class="{ 'selected-item': item.selected }">
          <!-- 勾选框 -->
          <div class="item-select">
            <label class="checkbox-label">
              <input
                  type="checkbox"
                  v-model="item.selected"
                  class="custom-checkbox"
              >
              <span class="checkmark"></span>
            </label>
          </div>

          <!-- 商品信息区域 -->
          <div class="item-info">
            <!-- 店铺名 -->
            <div class="shop-name font-bold">{{ item.shopName }}</div>

            <!-- 商品详情行 -->
            <div class="product-details">
              <!-- 商品图片 -->
              <div class="img-container">
                <img
                    :src="item.productImage || 'https://via.placeholder.com/80x80?text=暂无图片'"
                    :alt="item.productName"
                    class="product-img"
                    loading="lazy"
                >
                <div class="img-loading" v-if="!item.productImage"></div>
              </div>

              <!-- 商品名称和规格 -->
              <div class="product-info">
                <div class="product-name">{{ item.productName }}</div>
                <div class="product-sku" v-if="item.sku">
                  规格: {{ item.sku }}
                </div>
              </div>
            </div>
          </div>

          <!-- 单价 -->
          <div class="item-price">¥{{ item.price.toFixed(2) }}</div>

          <!-- 数量控制器 -->
          <div class="item-quantity">
            <button @click="handleDecrease(item)" :disabled="item.count <= 1" class="qty-btn minus">
              <i class="icon-minus"></i>
            </button>
            <input type="number" v-model="item.count" @change="handleCountChange(item)" class="qty-input">
            <button @click="handleIncrease(item)" class="qty-btn plus">
              <i class="icon-plus"></i>
            </button>
          </div>

          <!-- 小计 -->
          <div class="item-subtotal">
            <span class="price-highlight">¥{{ (item.price * item.count).toFixed(2) }}</span>
          </div>

          <!-- 操作按钮 -->
          <div class="item-operation">
            <button @click="handleDelete(item.id)" class="delete-btn">
              <i class="icon-delete"></i>
              <span class="delete-text">删除</span>
            </button>
          </div>
        </div>
      </transition-group>
    </div>

    <!-- 空购物车状态 -->
    <div class="empty-cart" v-else>
      <div class="empty-icon">
        <i class="icon-empty"></i>
      </div>
      <p class="empty-text">购物车还是空的，快去添加商品吧~</p>
      <button class="go-shopping">去逛逛</button>
    </div>

    <!-- 结算区域 -->
    <div class="cart-footer" v-if="cartItems.length > 0">
      <div class="total-info">
        <p>已选 <span class="selected-count">{{ selectedCount }}</span> 件商品</p>
        <p>合计:
          <span class="total-price">¥{{ totalPrice.toFixed(2) }}</span>
          <span class="tax-hint">（不含运费及税费）</span>
        </p>
      </div>
      <button @click="handleCheckout" class="checkout-btn" :disabled="selectedCount === 0">
        结算
        <i class="icon-arrow-right"></i>
      </button>
    </div>
  </div>
</template>


<script setup>
import { ref, computed, watch, onMounted } from 'vue';
import axios from 'axios';
import router from "@/router/index.js";
import { useRouter } from 'vue-router';
import { AuthService } from '@/service/auth.ts'
const authService = new AuthService();


// 购物车数据
const cartItems = ref([]);
// 全选状态
const selectAll = ref(false);
// 用户ID（实际项目从登录信息获取）
const userId = ref(authService.getUserId());
console.log(userId.value);

// 初始化加载购物车数据
onMounted(() => {
  fetchCartDetails();
});

// 获取购物车数据
const fetchCartDetails = async () => {
  try {
    const response = await axios.get(`/api/shopCar/details/${userId.value}`);
    if (response.data.code === 200) {
      // 为每个商品添加选中状态
      cartItems.value = (response.data.data || []).map(item => ({
        ...item,
        selected: true
      }));
      // 更新全选状态
      updateSelectAllStatus();
    }
  } catch (error) {
    console.error('获取购物车失败:', error);
  }
};

// 更新全选状态
const updateSelectAllStatus = () => {
  if (cartItems.value.length === 0) {
    selectAll.value = false;
    return;
  }
  selectAll.value = cartItems.value.every(item => item.selected);
};

// 监听商品选中状态变化
watch(
    () => cartItems.value,
    (newVal) => {
      updateSelectAllStatus();
    },
    { deep: true }
);

// 监听全选状态变化
watch(
    selectAll,
    (newVal) => {
      cartItems.value.forEach(item => {
        item.selected = newVal;
      });
    }
);

// 计算选中商品总数
const selectedCount = computed(() => {
  return cartItems.value.reduce((sum, item) => {
    return item.selected ? sum + item.count : sum;
  }, 0);
});

// 计算选中商品总价
const totalPrice = computed(() => {
  return cartItems.value.reduce((sum, item) => {
    return item.selected ? sum + (item.price * item.count) : sum;
  }, 0);

});

// 减少数量
const handleDecrease = async (item) => {
  if (item.count <= 1) return;
  item.count--;
  await updateCartItem(item);
};

// 增加数量
const handleIncrease = async (item) => {
  item.count++;
  await updateCartItem(item);
};

// 数量输入变化
const handleCountChange = async (item) => {
  if (item.count < 1) item.count = 1;
  await updateCartItem(item);
};

// 更新购物车项
const updateCartItem = async (item) => {
  try {
    await axios.put('/api/shopCar', {
      id: item.id,
      userId: userId.value,
      productId: item.productId,
      sku: item.sku,
      count: item.count,
      price: item.price,
      shopId: item.shopId
    });
  } catch (error) {
    console.error('更新购物车失败:', error);
    // 失败时回滚数据
    fetchCartDetails();
  }
};

// 删除商品
const handleDelete = async (id) => {
  if (confirm('确定要删除该商品吗？')) {
    try {
      await axios.delete(`http://localhost:8085/shopCar/${id}`);
      cartItems.value = cartItems.value.filter(item => item.id !== id);
    } catch (error) {
      console.error('删除失败:', error);
    }
  }
};

// 清空购物车
const handleClearAll = async () => {
  if (confirm('确定要清空购物车吗？')) {
    try {
      const ids = cartItems.value.map(item => item.id);
      await axios.delete('/api/shopCar/batch', { data: ids });
      cartItems.value = [];
    } catch (error) {
      console.error('清空失败:', error);
    }
  }
};

// 结算
// 结算
const handleCheckout = async () => {
  if (selectedCount.value === 0) {
    alert('请选择要结算的商品');
    return;
  }

  try {
    // 先调用原有的checkout接口（如果需要）
    const selectedIds = cartItems.value
        .filter(item => item.selected)
        .map(item => item.id);

    const checkoutResponse = await axios.post('/api/shopCar/checkout', selectedIds);
    if (checkoutResponse.data.code === 200) {
      console.log('购物车结算准备完成');
    }

    // 获取选中的商品项
    const selectedItems = cartItems.value.filter(item => item.selected);

    // 构造订单数据
    const orderData = {
      order: {
        userId: userId.value,
        totalAmount:parseFloat(totalPrice.value.toFixed(2)), // 确保金额精确到两位小数
        status: 0, // 0表示待支付
        addressId:0,
        createTime: new Date(),
        updateTime: new Date()
      },
      orderDetails: selectedItems.map(item => ({
        productId: item.productId,
        count: item.count,
        priceAfter: item.price,
        shopId: item.shopId,
        sku: item.sku
      }))
    };

    console.log('订单数据：', orderData);

    // 调用订单服务创建订单
    const orderResponse = await axios.post('/api/order/ordertb/create', orderData);

    if (orderResponse.data > 0) {
      const orderId = orderResponse.data;
      alert('订单创建成功，订单号：' + orderId);
      console.log('订单创建成功，订单号：', orderId);

      // 删除已结算的购物车商品
      const selectedIds = selectedItems.map(item => item.id);
      await axios.delete('/api/shopCar/batch', { data: selectedIds });

      // 从购物车列表中移除已结算的商品
      cartItems.value = cartItems.value.filter(item => !item.selected);

      // 实际项目中使用路由跳转到支付页面
       await router.push(`/Pay?orderId=${orderId}`);
    }
  } catch (error) {
    console.error('结算失败:', error);
    alert('结算失败，请重试');
  }
};

</script>

<style scoped>
/* 基础变量定义 */

.cart-container {
  --primary-color: #ff4d4f;
  --primary-light: #fff2f0;
  --primary-dark: #f5222d;
  --primary-opacity: rgba(255, 77, 79, 0.1);
  --text-primary: #333;
  --text-secondary: #666;
  --text-tertiary: #999;
  --border-color: #eee;
  --border-dark: #ddd;
  --border-hover: #ffccc7;
  --bg-light: #f9f9f9;
  --bg-white: #fff;
  --shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
  --shadow-hover: 0 4px 16px rgba(0, 0, 0, 0.08);
  --transition: all 0.25s ease;
  --radius: 8px;

  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  font-family: "PingFang SC", "Helvetica Neue", Arial, sans-serif;
  color: var(--text-primary);
}

/* 页面标题部分 */
.cart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 2px solid var(--border-color);
}

.cart-header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: var(--text-primary);
  position: relative;
  padding-left: 14px;
}

.cart-header h2::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 24px;
  background-color: var(--primary-color);
  border-radius: 2px;
}

.clear-btn {
  background-color: transparent;
  border: 1px solid var(--border-dark);
  padding: 9px 18px;
  border-radius: var(--radius);
  cursor: pointer;
  color: var(--text-secondary);
  font-size: 14px;
  display: inline-flex;
  align-items: center;
  gap: 6px;
  transition: var(--transition);
}

.clear-btn:enabled:hover {
  background-color: var(--primary-light);
  border-color: var(--primary-color);
  color: var(--primary-color);
  transform: translateY(-1px);
}

/* 列表头部 - 重点美化部分 */
.cart-list-header {
  display: flex;
  height: 60px;
  align-items: center;
  background: linear-gradient(180deg, #fcfcfc 0%, #f5f5f5 100%);
  border: 1px solid var(--border-color);
  border-bottom: 1px solid #e0e0e0;
  font-size: 14px;
  color: var(--text-secondary);
  padding: 0 24px;
  border-radius: var(--radius) var(--radius) 0 0;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.02);
  position: relative;
  overflow: hidden;
}

/* 表头装饰线 */
.cart-list-header::after {
  content: '';
  position: absolute;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 1px;
  background: linear-gradient(90deg,
  transparent 0%,
  rgba(0,0,0,0.05) 5%,
  rgba(0,0,0,0.05) 95%,
  transparent 100%);
}

/* 表头列样式增强 */
.cart-list-header > div {
  position: relative;
  z-index: 1;
  font-weight: 500;
  letter-spacing: 0.3px;
}

/* 列布局定义 */
.header-select, .item-select {
  width: 60px;
  padding: 0 10px;
}

.header-info, .item-info {
  flex: 3;
  padding: 0 15px;
}

.header-price, .item-price {
  width: 140px;
  text-align: center;
}

.header-quantity, .item-quantity {
  width: 160px;
  text-align: center;
}

.header-subtotal, .item-subtotal {
  width: 140px;
  text-align: center;
  font-weight: bold;
}

.header-operation, .item-operation {
  width: 100px;
  text-align: center;
}

/* 商品项样式 */
.cart-item {
  display: flex;
  align-items: center;
  padding: 20px;
  border: 1px solid var(--border-color);
  border-top: none;
  background-color: var(--bg-white);
  transition: var(--transition);
}

.cart-item:last-child {
  border-radius: 0 0 var(--radius) var(--radius);
}

.cart-item:hover {
  background-color: #fafafa;
  box-shadow: var(--shadow-hover);
  transform: translateY(-2px);
  border-color: var(--border-hover);
}

.cart-item.selected-item {
  background-color: var(--primary-opacity);
  border-color: var(--border-hover);
}

/* 其他样式保持不变 */
.shop-name {
  margin-bottom: 10px;
  color: var(--text-primary);
  font-size: 14px;
  padding-left: 2px;
}

.font-bold {
  font-weight: 600;
}

.product-details {
  display: flex;
  align-items: center;
}

.img-container {
  width: 88px;
  height: 88px;
  border-radius: var(--radius);
  overflow: hidden;
  margin-right: 16px;
  background-color: #f5f5f5;
  position: relative;
  box-shadow: 0 1px 3px rgba(0,0,0,0.05);
}

.product-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: var(--transition);
}

.product-img:hover {
  transform: scale(1.08);
}

.img-loading {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, #f0f0f0 25%, #f8f8f8 50%, #f0f0f0 75%);
  background-size: 200% 100%;
  animation: loading 1.5s infinite;
}

@keyframes loading {
  0% { background-position: 200% 0; }
  100% { background-position: -200% 0; }
}

.product-info {
  min-width: 0;
  padding: 5px 0;
}

.product-name {
  color: var(--text-primary);
  margin-bottom: 6px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  font-size: 14px;
  transition: var(--transition);
  line-height: 1.5;
}

.product-name:hover {
  color: var(--primary-color);
  text-decoration: underline;
}

.product-sku {
  color: var(--text-tertiary);
  font-size: 12px;
  line-height: 1.4;
}

.item-quantity {
  display: flex;
  justify-content: center;
  align-items: center;
}

.qty-btn {
  width: 32px;
  height: 32px;
  border: 1px solid var(--border-dark);
  background-color: var(--bg-white);
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: var(--transition);
  font-size: 16px;
}

.qty-btn.minus {
  border-radius: var(--radius) 0 0 var(--radius);
}

.qty-btn.plus {
  border-radius: 0 var(--radius) var(--radius) 0;
}

.qty-btn:hover {
  background-color: var(--primary-light);
  border-color: var(--primary-color);
  color: var(--primary-color);
}

.qty-input {
  width: 56px;
  height: 32px;
  text-align: center;
  border: 1px solid var(--border-dark);
  border-left: none;
  border-right: none;
  transition: var(--transition);
  font-size: 14px;
}

.delete-btn {
  color: var(--text-secondary);
  background: none;
  border: none;
  cursor: pointer;
  font-size: 14px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
  padding: 6px 10px;
  border-radius: var(--radius);
  transition: var(--transition);
}

.delete-btn:hover {
  color: var(--primary-color);
  background-color: var(--primary-light);
  transform: translateY(-1px);
}

.empty-cart {
  text-align: center;
  padding: 80px 0;
  color: var(--text-tertiary);
  border: 1px solid var(--border-color);
  background-color: var(--bg-white);
  border-radius: var(--radius);
  margin-bottom: 20px;
  box-shadow: var(--shadow);
  transition: var(--transition);
}

.empty-icon {
  font-size: 80px;
  color: #e8e8e8;
  margin-bottom: 24px;
  transition: var(--transition);
}

.empty-text {
  font-size: 16px;
  margin-bottom: 36px;
  color: var(--text-secondary);
  line-height: 1.6;
}

.go-shopping {
  background-color: var(--primary-color);
  color: white;
  border: none;
  padding: 12px 30px;
  border-radius: var(--radius);
  font-size: 14px;
  cursor: pointer;
  transition: var(--transition);
  box-shadow: 0 2px 8px rgba(255,77,79,0.2);
}

.cart-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 24px;
  padding: 20px 24px;
  background-color: var(--bg-white);
  border: 1px solid var(--border-color);
  border-radius: var(--radius);
  box-shadow: var(--shadow);
  transition: var(--transition);
}

.total-price {
  color: var(--primary-color);
  font-size: 24px;
  font-weight: 600;
  margin: 0 5px;
}

.checkout-btn {
  background-color: var(--primary-color);
  color: white;
  border: none;
  padding: 14px 40px;
  border-radius: var(--radius);
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  display: inline-flex;
  align-items: center;
  gap: 8px;
  transition: var(--transition);
}

.checkbox-label {
  display: inline-flex;
  align-items: center;
  white-space: nowrap;
  cursor: pointer;
  gap: 8px;
}

.custom-checkbox {
  position: absolute;
  opacity: 0;
  width: 0;
  height: 0;
}

.checkmark {
  position: relative;
  display: inline-block;
  width: 20px;
  height: 20px;
  /*border: 1px solid var(--border-dark);*/
  border: 1px solid #000;
  border-radius: 4px;
  background-color: var(--bg-white);
  transition: var(--transition);
}

.custom-checkbox:checked ~ .checkmark {
  background-color: var(--primary-color);
  border-color: var(--primary-color);
  animation: checkAnim 0.2s ease;
}

.checkmark:after {
  content: "";
  position: absolute;
  display: none;
  left: 6px;
  top: 2px;
  width: 5px;
  height: 10px;
  border: solid white;
  border-width: 0 2px 2px 0;
  transform: rotate(45deg);
}

.custom-checkbox:checked ~ .checkmark:after {
  display: block;
}

.cart-item-enter-active,
.cart-item-leave-active {
  transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
}

.cart-item-enter-from,
.cart-item-leave-to {
  opacity: 0;
  transform: translateY(10px) scale(0.98);
  box-shadow: none;
}

.price-highlight {
  color: var(--primary-color);
  font-weight: 600;
}

.icon-trash, .icon-delete, .icon-plus, .icon-minus, .icon-arrow-right, .icon-empty {
  display: inline-block;
}

.icon-trash::before { content: "🗑️"; }
.icon-delete::before { content: "🗑️"; }
.icon-plus::before { content: "+"; }
.icon-minus::before { content: "-"; }
.icon-arrow-right::before { content: "→"; }
.icon-empty::before { content: "🛒"; }

@keyframes checkAnim {
  0% { transform: scale(0.8); }
  50% { transform: scale(1.2); }
  100% { transform: scale(1); }
}

@media (max-width: 768px) {
  .cart-container {
    padding: 10px;
  }

  .cart-list-header {
    display: none;
  }

  .cart-item {
    flex-wrap: wrap;
    padding: 15px;
    position: relative;
    margin-bottom: 12px;
    border-radius: var(--radius);
  }

  .item-select {
    position: absolute;
    left: 15px;
    top: 15px;
  }

  .item-info {
    flex: 100%;
    margin-left: 50px;
    margin-bottom: 15px;
  }

  .item-price,
  .item-quantity,
  .item-subtotal,
  .item-operation {
    width: 25%;
    text-align: left;
    font-size: 13px;
  }

  .delete-text {
    display: none;
  }

  .cart-footer {
    flex-wrap: wrap;
    gap: 15px;
    padding: 15px;
  }

  .total-info {
    width: 100%;
  }

  .checkout-btn {
    width: 100%;
    justify-content: center;
  }
}
</style>
